matplotlib[07]绘制双坐标轴

摘要

matplotlib面向对象绘图,可以自由定义各种元素。这里讲解绘制双坐标轴。

数据

  • 数据内容如下表
x1-index x2-frameid y
1 10 1
2 24 4
3 42 2
4 56 3
5 76 1

以上数据存放在文件data.txt 中。

绘制X2-Y 折线图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!python2


import fire
import os
from glob import glob
#output a finally static picture of network
import networkx as nx
import pylab
from pprint import pprint
import matplotlib.pyplot as plt
import matplotlib
import matplotlib as mpl



#read data
fh=open("data.txt")

text = fh.readlines()[1:]

x1s=map(lambda i: i.split()[0],text)
x2s=map(lambda i: i.split()[1],text)
y1s=map(lambda i: i.split()[2],text)

fig = plt.figure()

ax1 = fig.add_subplot(111)
ax1.plot(x2s,y1s)

plt.show()

添加x1坐标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!python2
import fire
import os
from glob import glob
#output a finally static picture of network
import networkx as nx
import pylab
from pprint import pprint
import matplotlib.pyplot as plt
import matplotlib
import matplotlib as mpl

#read data
fh=open("data.txt")
text = fh.readlines()[1:]

x1s=map(lambda i: i.split()[0],text)
x2s=map(lambda i: i.split()[1],text)
y1s=map(lambda i: i.split()[2],text)

fig = plt.figure()

ax1 = fig.add_subplot(111)
ax1.plot(x2s,y1s)


ax2 = ax1.twiny() # this is the important function
ax2.set_xlabel('frame order from 1')
ax2.set_xlim(ax1.get_xlim())
print "ax1 lim",ax1.get_xlim()
print "ax1 ticks",ax1.get_xticks()
pprint(x1s)
ax2.set_xticks( ax1.get_xticks())
ax2.set_xticklabels(x1s)

plt.show()


# refer : https://stackoverflow.com/questions/10514315/how-to-add-a-second-x-axis-in-matplotlib

关键函数

  • ax.twiny () 共享Y坐标,添加新的x轴
  • ax.twinx () 共享X坐标,添加新的Y轴

突破点

  • 获得原来坐标的范围赋予新坐标
    ax2.set_xlim(ax1.get_xlim())
  • 获得原来坐标的tick位置赋予新坐标
    ax2.set_xticks( ax1.get_xticks())
  • 修改新坐标的ticklabel
    ax2.set_xticklabels(x1s)

总结

matplotlib 一切皆有可能。

参考

  1. https://stackoverflow.com/questions/10514315/how-to-add-a-second-x-axis-in-matplotlib